import { Button, Spin, Tooltip } from 'antd';
import cls from 'classnames';
import { Header } from 'gantd';
import { debounce } from 'lodash';
import React, { useCallback, useEffect, useImperativeHandle, useRef, useState } from 'react';
import ReactResizeDetector from 'react-resize-detector';
import { Form } from './subcomponents';
import { resolveValue } from './utils';
import styles from './index.less';

export default React.forwardRef(function SearchForm(props, ref: any) {
  const {
    searchKey,
    title,
    onSearch,
    onSmartSearch,
    onSizeChange,
    extra,
    customComponents = [],
    uiSchema = {},
    customBody,
    schema,
    headerProps = {},
    initParams = {},
    onValueChange = () => {},
    onReset,
    style,
    loading = false,
    headerExtraAfter = null,
  } = props;

  const [formKey] = useState(Date.now()); // 传递给 SchemaForm 的key，用于处理存在依赖时不能正常设值, 注意用state保持不变
  const [params, setParams] = useState<any>(initParams);
  const [formWidth, setFormWidth] = useState(0);
  const wrapperRef = useRef<HTMLDivElement>({ clientHeight: 0, clientWidth: 0 });
  const formRef = useRef<any>(null);
  const formNodeRef = useRef<any>(null);

  // 验证表单
  const validateFields = useCallback(async () => {
    const { validateFields } = formRef.current?.props?.form;
    let isValidateSuccess = false;
    if (!validateFields) {
      isValidateSuccess = true;
      return isValidateSuccess;
    }
    try {
      const validateRes: any = await validateFields();
      if (_.isEmpty(validateRes?.errors)) {
        isValidateSuccess = true;
      }
    } catch (error) {
      console.error(error);
    }
    return isValidateSuccess;
  }, []);

  // 查询方法的实现
  const onSearchMethord = useCallback(
    async (searchParams) => {
      if (loading) {
        return;
      }
      const isValidateSuccess = await validateFields();
      if (isValidateSuccess) {
        onSearch?.({
          ...params,
          ...searchParams,
        });
        onSmartSearch?.({
          ...params,
          ...searchParams,
        });
      }
    },
    [loading, params, validateFields, onSearch, onSmartSearch],
  );

  // 查询按钮点击防抖
  const onSearchClick = debounce((searchParams) => {
    onSearchMethord(searchParams);
  }, 300);

  // 点击重置表单
  const clickReset = useCallback(() => {
    if (loading) {
      return;
    }
    onReset?.();
  }, [onReset, loading]);

  // 输入值改变的回调
  const onValuesChange = useCallback(
    (values: any, allValues: any) => {
      const filterItems = resolveValue({
        params: allValues,
        schema,
        type: 'filter',
        isNormalSearch: true,
      });
      const searchItems = resolveValue({
        params: allValues,
        schema,
        type: 'search',
        isNormalSearch: true,
      });
      setParams(allValues);
      onValueChange(filterItems, searchItems);
    },
    [onValueChange, schema],
  );

  // 内容大小变化
  const onResize = useCallback(
    (width: number, height: number) => {
      onSizeChange?.({ width, height });
      setFormWidth(width);
    },
    [onSizeChange],
  );

  // 给ref对象添加方法
  useImperativeHandle(
    ref,
    () => {
      return {
        getParams: () => params,
        reset: clickReset,
        search: onSearchClick,
        validate: validateFields,
        getFormNode: () => formNodeRef.current,
        getFormRef: () => formRef.current,
      };
    },
    [params, clickReset, onSearchClick, validateFields],
  );

  // 动态计算宽高
  useEffect(() => {
    const { clientWidth: width, clientHeight: height } = wrapperRef.current;
    onSizeChange?.({ width, height });
    setFormWidth(width);
  }, [onSizeChange]);

  return (
    <div
      ref={wrapperRef}
      className={cls(styles.wrapper, styles['view-picker-wrapper'], 'gant-searchform')}
      style={style}
    >
      <ReactResizeDetector handleWidth handleHeight onResize={onResize}>
        <Spin spinning={loading}>
          <Header
            type=""
            title={title}
            size="small"
            extra={
              <>
                {extra}
                <Tooltip title={'查询'}>
                  <Button size="small" icon="search" type="primary" onClick={() => onSearchClick()} />
                </Tooltip>
                <Tooltip title={'重置'}>
                  <Button size="small" icon="undo" onClick={clickReset} className="marginh5" />
                </Tooltip>
                {headerExtraAfter}
              </>
            }
            {...headerProps}
          />
          <div className={styles.formWrapper}>
            <div className={cls(styles.formBody, styles.borderBottom)}>
              <Form
                formRef={formRef}
                onValuesChange={onValuesChange}
                customComponents={customComponents}
                uiSchema={uiSchema}
                schema={schema}
                width={formWidth}
                formNodeRef={formNodeRef}
                searchKey={searchKey}
                formKey={formKey}
              />
            </div>
            <div className={cls(styles.formBody, styles.borderBottom, styles.formBodyHidden)}>{customBody}</div>
          </div>
        </Spin>
      </ReactResizeDetector>
    </div>
  );
});
